package t1dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import t1bean.MajorBean;
import t1jdbc.JDBCUtil;

public class MajorActionDao {

	private Connection conn = null;
	private PreparedStatement ps = null;
	private ResultSet rs = null;
	private SetSql ss=new SetSql();

	/**
	 * @param major
	 * @return	
	 * @throws SQLException
	 * 
	 * 插入
	 */
	public int insert(MajorBean major) throws SQLException {
		String sql = "insert into major(number,name) values(?,?)";
		try {
			conn = JDBCUtil.getConnection();
			ps = conn.prepareStatement(sql);
			conn.setAutoCommit(false);
			ps.setInt(1, major.getNumber());
			ps.setString(2, major.getName());
			int i = ps.executeUpdate(sql);
			conn.commit();
			return i;
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
			conn.rollback();
		} finally {
			JDBCUtil.close(conn, ps);
			conn = null;
			ps = null;
		}
		return 0;
	}

	/**
	 * @param major
	 * @return List<MajorBean>
	 * @throws SQLException
	 * 查询
	 */
	public List<MajorBean> select(MajorBean major) throws SQLException {
		String sql = "select * from major where ";
		List<MajorBean> list=new ArrayList<>();
		try {
			conn = JDBCUtil.getConnection();
			List<Object> oList=new ArrayList<>();
			sql=ss.setSql(major,oList, sql, 2);
//			System.out.println(sql);
			conn.setAutoCommit(false);
			ps = conn.prepareStatement(sql);
			for(int i=0;i<oList.size();i++) {
				ps.setObject(i+1, oList.get(i));
			}
			rs = ps.executeQuery();
			while(rs.next()) {
				MajorBean major1=new MajorBean();
				major1.setId(rs.getInt("id"));
				major1.setName(rs.getString("name"));
				major1.setNumber(rs.getInt("number"));
				list.add(major1);
			}
			conn.commit();
			return list;
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
			conn.rollback();
		} finally {
			JDBCUtil.close(conn, ps, rs);
		}
		return list;

	}
	
	
}
